/**
 * 注册组件
 * */

import {Form} from "antd";
import {connect} from "react-redux";
import React, {Component} from "react";
import {withRouter} from "react-router-dom";

import {register} from "src/api/request";
import RegisterForm from "src/components/RegisterForm/RegisterForm";
import LoginRegisterBottom from "src/components/Bottom/LoginRegisterBottom/LoginRegisterBottom";

class Register extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      username: '',
      password: '',
      full_name: '',
      errorInfo: {},
      isLoading: false,
      accepted_terms: false,
    };
  }

  /**
   * 表单提交成功
   * */
  onFinish = values => {
    this.setState({
      errorInfo: {},
      isLoading: true,
      full_name: values.fullName,
      email: values.email,
      username: values.username,
      password: values.password,
      accepted_terms: values.accepted_terms,
    });
    this.props.register(this.state).then(
      () => {
        this.props.history.push('/login')
      },
      () => {
        this.props.history.push('/register');
        this.setState({
          isLoading: false,
        });
      },
    )
  };

  /**
   * 表单提交失败（表单验证失败）
   * */
  onFinishFailed = errorInfo => {
    console.log("errorInfo", errorInfo)
  };

  // 跳转到登录路由
  toLogin = () => {
    this.props.history.replace('/login')
  };


  render() {
    const {status} = this.state.isLoading;
    return (
      <div className='register'>
        <Form
          layout='horizontal'
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          scrollToFirstError
        >
          <RegisterForm status={status}/>
        </Form>
        <div className={'link'}>
          <span>已有账号？</span>
          <span onClick={this.toLogin}>登录</span>
        </div>
        <LoginRegisterBottom/>
      </div>
    )
  }
}

export default withRouter(connect(null, {register})(Register))